// 文章新建或者更新表单
import {Button, Form, Input, message, Modal, Upload, UploadFile, UploadProps} from "antd";
import {ArticleDataType, ArticleFormType} from "../../../../util/publicType";
import {useLocation, useNavigate, useParams} from "react-router-dom";
import React, {useEffect, useState} from "react";
import {addArticle, articleDetail, dictDetail, editArticle} from "../../../../api";
import {AxiosResponse} from "axios/index";
import {PlusOutlined} from "@ant-design/icons";
import {beforeUpload, getBase64} from "../../../../util";
import {RcFile} from "antd/es/upload";
import {BASE_UPLOAD_FILE} from "../../../../axios";
import WangEdit from "../../../../components/WangEdit";
import CategoryForm from "../../../../components/CategoryForm";
import {useAppSelector} from "../../../../Hooks";
import {RootState} from "../../../../store";

const FormArticle = () => {
    // 路由信息
    const l = useLocation();
    // 判断是否为更新页
    const isUpdate = l.pathname.indexOf("update") >= 0;
    // 表单
    const [stateForm] = Form.useForm();
    // 预览控制
    const [previewOpen, setPreviewOpen] = useState(false);
    // 预览地址
    const [previewImage, setPreviewImage] = useState('');
    // 预览标题
    const [previewTitle, setPreviewTitle] = useState('');
    // 上传图标列表
    const [coverList, setCoverList] = useState<UploadFile[]>([]);
    // 参数获取
    const {id} = useParams();
    // 路由
    const n = useNavigate();
    //编辑器原内容
    let oldEditData: string = '';
    // 编辑器新内容状态
    const [html, setHtml] = useState('') // 编辑器内容

    // 文章详情
    const [data, setData] = useState<ArticleDataType | null>(null);

    // 当前用户信息
    const info = useAppSelector((state: RootState) => state.info);

    // 文章详情
    const getDetail = () => {
        articleDetail(id as string).then((r: AxiosResponse) => {
            setData(r.data.data.data);
        }, err => message.error(err))
    }
    // 文件i变化
    const handleChange: UploadProps['onChange'] = ({fileList: newFileList}) => {
        setCoverList(newFileList);
    }

    // 上传按钮
    const uploadButton = (
        <div>
            <PlusOutlined/>
            <div style={{marginTop: 8}}>上传</div>
        </div>
    );

    // 上传事件
    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    };
    // 如果是更新页面才执行
    useEffect(() => {
        // 是否为更新页面
        if (isUpdate) {
            getDetail();
        }
        setHtml("")
    }, []);

    // 详情数据变化执行
    useEffect(() => {
        if (isUpdate) {
            stateForm.setFieldsValue(data);
            // 图片给值
            const coverList: any = {
                uid: data?.cover?.id,
                status: 'done',
                name: data?.cover?.type,
                url: data?.cover?.path
            };
            setCoverList([coverList]);
            setHtml(data?.content ?? '')
        }
    }, [data])

    // 完成
    const onFinish = (v: ArticleFormType) => {
        const cover_id = coverList[0]?.response?.data?.data?.id;
        v.cover_id = cover_id ? cover_id : coverList[0]?.uid;
        if (!v.cover_id) {
            return message.error("请上传封面")
        }
        v.content = html;
        // 从redux中读取
        v.username = info.username;
        let request: Promise<AxiosResponse>;
        if (isUpdate) {
            request = editArticle((id as string), v)
        } else {
            request = addArticle(v);
        }
        request.then(async () => {
            // 清除数据
            stateForm.resetFields();
            // 清除原本数据
            setCoverList([]);
            if (isUpdate) {
                n(`/article/${data?.category_id}`);
            }
            setHtml("");
            await message.success("操作成功");

        }, err => message.error(err))
    }

    return (
        <div style={{padding: "30px 0"}}>
            <Form
                style={{width: "90%", margin: "0 auto"}}
                form={stateForm}
                onFinish={onFinish}
                autoComplete="off"
            >
                <Form.Item
                    labelCol={{span: 3}}
                    label="上传封面"
                    name="cover_id"
                    rules={[{required: !(coverList.length >= 1), message: '请上传封面'}]}
                >
                    <Upload
                        accept="image/*"
                        action={BASE_UPLOAD_FILE}
                        listType="picture-card"
                        fileList={coverList}
                        beforeUpload={beforeUpload}
                        onPreview={handlePreview}
                        onChange={handleChange}
                    >
                        {coverList.length >= 1 ? null : uploadButton}
                    </Upload>
                </Form.Item>
                <Form.Item
                    labelCol={{span: 10}}
                    label="标题"
                    name="name"
                    style={{width: "30%"}}
                    rules={[{required: true, message: '请输入文章名字'}]}
                >
                    <Input/>
                </Form.Item>
                <Form.Item
                    labelCol={{span: 3}}
                    label="详细介绍"
                    name="content"
                    style={{width: "100%"}}
                >
                    {/*富文本组件*/}
                    <WangEdit
                        content={oldEditData ?? ''}
                        html={html} setHtml={setHtml}/>
                </Form.Item>
                {/*分类组件*/}
                <CategoryForm id={id as string}
                              spanValue={3}
                              detailData={data}/>
                <Form.Item wrapperCol={{offset: 10, span: 16}}>
                    <Button type="primary" htmlType="submit" style={{marginRight: "10px"}}>
                        提交
                    </Button>
                    <Button type="primary" htmlType="reset">
                        重置
                    </Button>
                </Form.Item>
            </Form>
            {/**/}
            <Modal open={previewOpen} title={previewTitle} footer={null}
                   onCancel={() => setPreviewOpen(false)}>
                <img alt="example" style={{width: '100%'}} src={previewImage}/>
            </Modal>
        </div>
    )
}

export default FormArticle;